package whf.framework.web.tag;

import javax.servlet.jsp.JspException;

import whf.framework.log.Log;
import whf.framework.log.LogFactory;
import whf.framework.mail.entity.Mail;
import whf.framework.mail.service.MailService;
import whf.framework.mail.service.MailServiceImp;
import whf.framework.util.StringUtils;

/**
 * 将Tag中的内容作为邮件内容发送
 * 
 * @author wanghaifeng
 * @create Nov 2, 2006 9:31:04 PM
 * 
 */
public class MailTag extends HtmlTag {
	private Log log = LogFactory.getLog(MailTag.class);
	
	private static MailService mailService;
	/**
	 * 主题
	 * 
	 * @property String:subject
	 */
	private String subject;

	/**
	 * 当前只是保存到数据库，以后在邮件任务中发送
	 * @property boolean:sendLater
	 */
	private boolean sendLater;
	/**
	 * 接收人
	 * 
	 * @property String:to
	 */
	private String to;

	/**
	 * 抄送
	 * 
	 * @property String:cc
	 */
	private String cc;

	/**
	 * 密送
	 * 
	 * @property String:bcc
	 */
	private String bcc;

	/**
	 * @param bcc The bcc to set.
	 */
	public void setBcc(String bcc) {
		this.bcc = bcc;
	}

	/**
	 * @param cc The cc to set.
	 */
	public void setCc(String cc) {
		this.cc = cc;
	}

	/**
	 * @param subject The subject to set.
	 */
	public void setSubject(String subject) {
		this.subject = subject;
	}

	/**
	 * @param to The to to set.
	 */
	public void setTo(String to) {
		this.to = to;
	}

	/**
	 * @param sendLater The sendLater to set.
	 */
	public void setSendLater(boolean sendLater) {
		this.sendLater = sendLater;
	}

	public int doStartTag() throws JspException{
		return 2;
	}
	
	public int doEndTag() throws JspException{
		if(this.getBodyContent() != null){
			String content = this.getBodyContent().getString();
			if(!StringUtils.isEmpty(content)){
				try{
					if(mailService == null){
						mailService = MailServiceImp.getMailService();
					}
					Mail mail = new Mail();
					mail.setName(this.subject);
					mail.setRemarks(content);
					mail.setTo(this.to);
					mail.setCc(this.cc);
					mail.setBcc(this.bcc);
					if(this.sendLater){
						mailService.create(mail);
					} else {
						mailService.send(mail);
					}
					super.println(content);
				}catch(Exception e){
					log.error(this, e);
					super.println("<div align='left'><font size='5' color='red'>Mail send failure, cause by the flowing reason:</font></div>");
					super.println("<pre>");
					super.println(StringUtils.getExceptionDetail(e));
					super.println("</pre>");
				}
			}
		}
		this.release();
		return SKIP_BODY;
	}
	
	public void release() {
		this.subject = null;
		this.to = null;
		this.cc = null;
		this.bcc = null;
		super.release();
	}
}
